package com.example.lotterysystem.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil {

    private final static Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    /**
     * RedisTemplate: 先将被存储的数据转换成字节数组（不可读），再存储到redis中，读取的时候按照字节数组读取
     * StringRedisTemplate： 直接存放的就是string（可读）
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 设置key-value
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try{
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
logger.error("RedisUtil error,set({},{})", key, value,e);
            return false;
        }
    }

    /**
     * 设置key-value，并设置过期时间
     * @param key
     * @param value
     * @param expireTime
     * @return
     */
    public boolean set(String key, String value,Long expireTime) {
        try{
            stringRedisTemplate.opsForValue().set(key, value,expireTime, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil error,set({},{},{})", key, value,expireTime,e);
            return false;
        }
    }

    /**
     * 获取key对应的value
     * @param key
     * @return
     */
    public String get(String key) {
try{
    return StringUtils.hasText(key)?stringRedisTemplate.opsForValue().get(key):null;
}catch (Exception e) {
    logger.error("RedisUtil error,get({})", key,e);
}
return null;
    }


    /**
     * 删除key对应的value
     * @param key
     * @return
     */
    public boolean delete(String... key) {
        try{
            if(key!=null&&key.length>0){
                if (key.length==1){
                    stringRedisTemplate.delete(key[0]);
                }else{
                    stringRedisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
return true;
        }catch (Exception e) {
logger.error("RedisUtil error,delete({})", key,e);
return false;
        }
    }


    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        try{
            return StringUtils.hasText(key)?stringRedisTemplate.hasKey(key):false;
        }catch (Exception e){
            logger.error("RedisUtil error,hasKey({})", key,e);
            return false;
        }

    }



}
